package com.qf.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class QQServer {
	public static void main(String[] args) throws Exception{
		//1.开启网络侦听
		ServerSocket ss = new ServerSocket(9999);
		System.out.println("服务器已经开启侦听，准备接收客户端的连接...");
		while(true) {
			Socket socket =  ss.accept();//返回一个socket对象【负责和连接的远程客户进行通信的端口对象】
			System.out.println("当前连接过来的客户:" + socket);
			
			Thread reciveThread = new Thread(new Reciver(socket));
			reciveThread.start();
			
		}
		
	}
}

class Reciver implements Runnable{
	
	private Socket socket;
	

	public Reciver(Socket socket) {
		super();
		this.socket = socket;
	}


	@Override
	public void run() {
		//接收已经连接的客户发送过来的消息
		byte[] buffer = new byte[1024];
		//获取socket对象的输入流
		try {
			InputStream is= socket.getInputStream();
			
			String address=socket.getRemoteSocketAddress().toString();
			
			while(true) {
				int r=is.read(buffer);
				
				String message=new String(buffer, 0, r, "utf-8");
				
				//客户端发送的message消息分为两种情况：1.正在登录  2.正在发送消息
				
				if(message.startsWith("login:")) {
					//说明当前客户正在登录
					SessionManager.login(address, new ClientData(message.split(":")[1],socket));
					System.out.println("登录成功！");
				
					
				}else {
					//当前客户正在发送消息
					//判断当前用户是否已经登录
					
					boolean isLogin=SessionManager.checkLogin(address);
					
					if(isLogin) {
						//System.out.println(SessionManager.getUsername(address) + "发送一条消息:" +  message);
						//将客户发送的消息按照to:xxx:message指定的客户进行消息的转发
						String[] split=message.split(":");
						
						OutputStream outputStream=SessionManager.getSocketByUsername(split[1]).getOutputStream();
						
						
						outputStream.write((SessionManager.getUsername(address) + "对你说：" + split[2]).getBytes());
						
						
					}else {
						System.out.println("当前客户没有登录，不允许进行消息的发送！");
					}
				}
				
				
				

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}
